import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Progress } from './ui/progress';
import { ArrowRight, Clock, Trophy, Star, CheckCircle, XCircle } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { TestResult } from '../types';

interface SequenceReasoningTestProps {
  onComplete: (result: TestResult) => void;
}

interface Question {
  id: number;
  type: 'number' | 'shape' | 'pattern';
  sequence: (number | string)[];
  options: (number | string)[];
  correct: number | string;
  rule: string;
}

const NUMBER_QUESTIONS: Question[] = [
  {
    id: 1,
    type: 'number',
    sequence: [2, 4, 6, 8, '?'],
    options: [10, 12, 14, 16],
    correct: 10,
    rule: '连续偶数'
  },
  {
    id: 2,
    type: 'number',
    sequence: [1, 4, 9, 16, '?'],
    options: [20, 25, 30, 35],
    correct: 25,
    rule: '平方数'
  },
  {
    id: 3,
    type: 'number',
    sequence: [3, 6, 12, 24, '?'],
    options: [36, 42, 48, 54],
    correct: 48,
    rule: '每次乘2'
  },
  {
    id: 4,
    type: 'number',
    sequence: [1, 1, 2, 3, 5, '?'],
    options: [7, 8, 9, 10],
    correct: 8,
    rule: '斐波那契数列'
  },
  {
    id: 5,
    type: 'number',
    sequence: [2, 6, 18, 54, '?'],
    options: [108, 162, 180, 216],
    correct: 162,
    rule: '每次乘3'
  }
];

const SHAPE_QUESTIONS: Question[] = [
  {
    id: 6,
    type: 'shape',
    sequence: ['○', '●', '○', '●', '?'],
    options: ['○', '●', '◇', '◆'],
    correct: '○',
    rule: '交替模式'
  },
  {
    id: 7,
    type: 'shape',
    sequence: ['△', '□', '○', '△', '?'],
    options: ['□', '○', '△', '◇'],
    correct: '□',
    rule: '重复三角形-正方形-圆形'
  },
  {
    id: 8,
    type: 'shape',
    sequence: ['●', '●●', '●●●', '●●●●', '?'],
    options: ['●●●●●', '●●●', '●', '●●'],
    correct: '●●●●●',
    rule: '递增模式'
  }
];

const PATTERN_QUESTIONS: Question[] = [
  {
    id: 9,
    type: 'pattern',
    sequence: ['AB', 'BC', 'CD', 'DE', '?'],
    options: ['EF', 'FG', 'EA', 'DF'],
    correct: 'EF',
    rule: '连续字母对'
  },
  {
    id: 10,
    type: 'pattern',
    sequence: ['A1', 'B2', 'C3', 'D4', '?'],
    options: ['E5', 'F6', 'A5', 'D5'],
    correct: 'E5',
    rule: '字母+数字递增'
  }
];

const ALL_QUESTIONS = [...NUMBER_QUESTIONS, ...SHAPE_QUESTIONS, ...PATTERN_QUESTIONS];

export function SequenceReasoningTest({ onComplete }: SequenceReasoningTestProps) {
  const [stage, setStage] = useState<'instructions' | 'test' | 'results'>('instructions');
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [selectedAnswer, setSelectedAnswer] = useState<number | string | null>(null);
  const [answers, setAnswers] = useState<(number | string | null)[]>(new Array(ALL_QUESTIONS.length).fill(null));
  const [timeLeft, setTimeLeft] = useState(480); // 8分钟
  const [startTime, setStartTime] = useState<number>(0);
  const [showFeedback, setShowFeedback] = useState(false);
  const [feedbackCorrect, setFeedbackCorrect] = useState(false);

  const question = ALL_QUESTIONS[currentQuestion];

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (stage === 'test' && timeLeft > 0) {
      interval = setInterval(() => {
        setTimeLeft(prev => {
          if (prev <= 1) {
            setStage('results');
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [stage, timeLeft]);

  const handleStartTest = () => {
    setStage('test');
    setStartTime(Date.now());
  };

  const handleAnswerSelect = (answer: number | string) => {
    setSelectedAnswer(answer);
  };

  const handleSubmitAnswer = () => {
    if (selectedAnswer === null) return;

    const newAnswers = [...answers];
    newAnswers[currentQuestion] = selectedAnswer;
    setAnswers(newAnswers);

    // 显示反馈
    const isCorrect = selectedAnswer === question.correct;
    setFeedbackCorrect(isCorrect);
    setShowFeedback(true);

    setTimeout(() => {
      setShowFeedback(false);
      setSelectedAnswer(null);

      if (currentQuestion < ALL_QUESTIONS.length - 1) {
        setCurrentQuestion(prev => prev + 1);
      } else {
        setStage('results');
      }
    }, 1500);
  };

  const handleComplete = () => {
    const correctAnswers = answers.filter((answer, index) => 
      answer === ALL_QUESTIONS[index].correct
    ).length;
    
    const finalScore = Math.round((correctAnswers / ALL_QUESTIONS.length) * 100);
    const timeUsed = Math.round((Date.now() - startTime) / 1000);

    const result: TestResult = {
      id: Date.now().toString(),
      testType: 'sequence-reasoning',
      score: finalScore,
      completedAt: new Date(),
      duration: timeUsed,
      details: {
        totalQuestions: ALL_QUESTIONS.length,
        correctAnswers,
        accuracy: Math.round((correctAnswers / ALL_QUESTIONS.length) * 100),
        timeUsed,
        averageTimePerQuestion: Math.round(timeUsed / ALL_QUESTIONS.length)
      }
    };

    onComplete(result);
  };

  if (stage === 'instructions') {
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-slate-200 shadow-lg">
          <CardHeader className="text-center pb-8">
            <div className="w-16 h-16 bg-gradient-to-br from-slate-500 to-gray-600 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <ArrowRight className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl text-slate-800">序列推理测试</CardTitle>
            <p className="text-slate-600 mt-2">测试您的数字和图形序列推理能力</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="bg-gradient-to-r from-slate-50 to-gray-50 rounded-xl p-6 border border-slate-200">
              <h3 className="font-semibold text-slate-900 mb-4 flex items-center gap-2">
                <Star className="w-5 h-5" />
                测试说明
              </h3>
              <div className="space-y-3 text-slate-700">
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-slate-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                  <p>观察给定的数字、图形或模式序列</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-slate-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                  <p>找出序列中的规律或模式</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-slate-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                  <p>选择正确的下一项完成序列</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-slate-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
                  <p>包含数字序列、图形模式和符号规律</p>
                </div>
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-slate-50 to-slate-100 rounded-xl border border-slate-200">
                <div className="text-2xl font-bold text-slate-600 mb-1">{ALL_QUESTIONS.length}</div>
                <div className="text-sm text-slate-700">题目数量</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-xl border border-gray-200">
                <div className="text-2xl font-bold text-gray-600 mb-1">8</div>
                <div className="text-sm text-gray-700">分钟限时</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-slate-50 to-gray-50 rounded-xl border border-slate-200">
                <div className="text-2xl font-bold text-slate-600 mb-1">3</div>
                <div className="text-sm text-slate-700">题目类型</div>
              </div>
            </div>

            <Button 
              onClick={handleStartTest}
              className="w-full bg-gradient-to-r from-slate-500 to-gray-600 hover:from-slate-600 hover:to-gray-700 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              开始测试
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'test') {
    const progress = ((currentQuestion) / ALL_QUESTIONS.length) * 100;

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-4xl mx-auto space-y-6"
      >
        {/* 顶部状态栏 */}
        <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
          <div className="flex items-center gap-4">
            <Badge variant="outline" className="bg-slate-100 text-slate-700 border-slate-300">
              第 {currentQuestion + 1} / {ALL_QUESTIONS.length} 题
            </Badge>
            <Badge variant="outline" className={`${
              question.type === 'number' ? 'bg-blue-100 text-blue-700 border-blue-300' :
              question.type === 'shape' ? 'bg-green-100 text-green-700 border-green-300' :
              'bg-purple-100 text-purple-700 border-purple-300'
            }`}>
              {question.type === 'number' ? '数字序列' :
               question.type === 'shape' ? '图形模式' : '符号规律'}
            </Badge>
          </div>
          
          <div className="flex items-center gap-2">
            <Clock className="w-4 h-4 text-slate-500" />
            <span className={`font-mono text-lg font-bold ${timeLeft <= 60 ? 'text-red-500' : 'text-slate-700'}`}>
              {Math.floor(timeLeft / 60)}:{(timeLeft % 60).toString().padStart(2, '0')}
            </span>
          </div>
        </div>

        <Progress value={progress} className="h-2" />

        {/* 题目卡片 */}
        <Card className="bg-white/90 backdrop-blur-sm border-slate-200 shadow-lg">
          <CardContent className="p-8">
            <div className="text-center mb-8">
              <h2 className="text-xl font-semibold text-slate-800 mb-6">
                找出下一项
              </h2>
              
              {/* 序列显示 */}
              <div className="flex items-center justify-center gap-4 mb-8">
                {question.sequence.map((item, index) => (
                  <React.Fragment key={index}>
                    <div className={`
                      min-w-16 h-16 rounded-xl border-2 border-dashed border-slate-300 
                      flex items-center justify-center
                      ${item === '?' ? 'bg-gradient-to-br from-slate-100 to-slate-200' : 'bg-white'}
                      ${question.type === 'shape' ? 'text-3xl' : 'text-xl font-bold text-slate-800'}
                    `}>
                      {item === '?' ? (
                        <span className="text-2xl text-slate-400">?</span>
                      ) : (
                        item
                      )}
                    </div>
                    {index < question.sequence.length - 1 && (
                      <ArrowRight className="w-4 h-4 text-slate-400" />
                    )}
                  </React.Fragment>
                ))}
              </div>
            </div>

            {/* 选项 */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 max-w-2xl mx-auto">
              {question.options.map((option, index) => (
                <motion.div
                  key={index}
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                >
                  <Button
                    variant={selectedAnswer === option ? "default" : "outline"}
                    onClick={() => handleAnswerSelect(option)}
                    className={`w-full h-16 text-lg ${
                      selectedAnswer === option 
                        ? 'bg-gradient-to-br from-slate-500 to-gray-600 text-white' 
                        : 'hover:bg-slate-50'
                    } ${question.type === 'shape' ? 'text-2xl' : 'font-bold'}`}
                  >
                    {option}
                  </Button>
                </motion.div>
              ))}
            </div>

            <div className="flex justify-center mt-8">
              <Button
                onClick={handleSubmitAnswer}
                disabled={selectedAnswer === null}
                className="bg-gradient-to-r from-slate-500 to-gray-600 hover:from-slate-600 hover:to-gray-700 text-white px-8 py-2 font-semibold"
              >
                提交答案
              </Button>
            </div>
          </CardContent>
        </Card>

        {/* 反馈弹窗 */}
        <AnimatePresence>
          {showFeedback && (
            <motion.div
              initial={{ opacity: 0, y: -20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              className="fixed top-20 left-1/2 transform -translate-x-1/2 z-50"
            >
              <Card className={`border-0 shadow-lg ${
                feedbackCorrect 
                  ? 'bg-green-500 text-white' 
                  : 'bg-red-500 text-white'
              }`}>
                <CardContent className="py-3 px-6">
                  <div className="flex items-center gap-2">
                    {feedbackCorrect ? (
                      <CheckCircle className="w-5 h-5" />
                    ) : (
                      <XCircle className="w-5 h-5" />
                    )}
                    <span className="font-semibold">
                      {feedbackCorrect ? '正确！' : '错误！'}
                    </span>
                    <span className="text-sm">
                      ({question.rule})
                    </span>
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          )}
        </AnimatePresence>
      </motion.div>
    );
  }

  if (stage === 'results') {
    const correctAnswers = answers.filter((answer, index) => 
      answer === ALL_QUESTIONS[index].correct
    ).length;
    const finalScore = Math.round((correctAnswers / ALL_QUESTIONS.length) * 100);
    const accuracy = Math.round((correctAnswers / ALL_QUESTIONS.length) * 100);

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-slate-200 shadow-xl">
          <CardHeader className="text-center pb-6">
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
              className="w-20 h-20 bg-gradient-to-br from-slate-500 to-gray-600 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
            >
              <Trophy className="w-10 h-10 text-white" />
            </motion.div>
            
            <CardTitle className="text-3xl text-slate-800 mb-2">测试完成！</CardTitle>
            <div className="text-6xl font-bold bg-gradient-to-r from-slate-500 to-gray-600 bg-clip-text text-transparent">
              {finalScore}
            </div>
            <p className="text-slate-600">序列推理能力得分</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="grid grid-cols-2 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-slate-50 to-slate-100 rounded-xl border border-slate-200">
                <div className="text-2xl font-bold text-slate-600 mb-1">{correctAnswers}/{ALL_QUESTIONS.length}</div>
                <div className="text-sm text-slate-700">正确题数</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-xl border border-gray-200">
                <div className="text-2xl font-bold text-gray-600 mb-1">{accuracy}%</div>
                <div className="text-sm text-gray-700">准确率</div>
              </div>
            </div>

            <div className="space-y-3">
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">数字序列</span>
                <span className="font-semibold text-slate-800">
                  {answers.slice(0, 5).filter((answer, i) => answer === ALL_QUESTIONS[i].correct).length}/5
                </span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">图形模式</span>
                <span className="font-semibold text-slate-800">
                  {answers.slice(5, 8).filter((answer, i) => answer === ALL_QUESTIONS[i + 5].correct).length}/3
                </span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">符号规律</span>
                <span className="font-semibold text-slate-800">
                  {answers.slice(8).filter((answer, i) => answer === ALL_QUESTIONS[i + 8].correct).length}/2
                </span>
              </div>
            </div>

            <Button 
              onClick={handleComplete}
              className="w-full bg-gradient-to-r from-slate-500 to-gray-600 hover:from-slate-600 hover:to-gray-700 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              查看详细结果
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  return null;
}